package com.zj.executor.result;

import com.zj.mapping.MappedStatement;
import com.zj.reflect.ReflectUtil;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;


public class SimpleResultHandler implements  ResultHandler{

    @Override
    public <T> List<T> handle(ResultSet resultSet, MappedStatement mappedStatement) throws Exception {
        String resultType = mappedStatement.getResultType();
        Class<?> resultTypeClass = ReflectUtil.getClassByType(resultType);
        List<Object> objects = new ArrayList<>();
        while (resultSet.next()){
            ResultSetMetaData metaData = resultSet.getMetaData();
            Object o = resultTypeClass.newInstance();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i);
                Object value = resultSet.getObject(columnName);
                ReflectUtil.setFieldValue(o,columnName,value);
            }
            objects.add(o);
        }
        return (List<T>) objects;
    }
}
